// subPages/health/bloodFat/bloodFat.js
import * as echarts from '../../../ec-canvas/echarts';
var util =  require('../../../utils/healthUtil.js');
var navListJson = require('../../../data/navListJson');
var indexJson = require('../../../data/indexJson');
var recordJson = require('../../../data/recordJson');
let LineChart = null
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0,
    ec: {
      // lazyLoad: true // 延迟加载
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setDate()
  },

  bindDateChange: function(e) {
    var that = this
    that.setData({
      date: e.detail.value,
    })
    that.getData(that.data.date)
  },

  //设置日期
  setDate:function(){
    var that = this
    let date = util.setTime10(new Date())
    let createtime = util.setTime(new Date())
    let Y = date.split('-')
    that.setData({
      createtime: createtime,
      date: date,
      dateStart: Y[0]- 3,
      dateEnd: date,
      thList: navListJson.bodyFatThList
    })
    that.getData(date)
  },
  

  //获得数据
  getData:function(date){
    var that = this
    wx.request({
        url: app.globalData.apiUrl +'/get_user_xuezhi',
        data: {
          userid: app.globalData.userId,
          time: date
        },
        method: 'get',
        header: {
          'content-type': 'application/json' //默认值
        },
        success: function (res) {
          // console.log(res)
          if(res.data.code == '200'){
            that.processingOneData(res.data.data);
            that.processingEchartData(res.data.data1);
            that.processingData(res.data.data);
          }else{
            util.showModal('提示','数据异常')
            return;
          }
        },
        fail: function (res) {
          console.log("失败",res);
        }
    })
  },

  //处理最新一条数据
  processingOneData:function(list){
    var that = this
    if(list.length != 0){
      var fatList = indexJson.fatList
      for(let i in fatList)
      {
        switch (fatList[i].index) {
          case 1:
            fatList[i].data = list[0].cholesterol
            break;
          case 2:
            fatList[i].data = list[0].glycerol
            break;
          case 3:
            fatList[i].data = list[0].uric
            break;
          case 4:
            fatList[i].data = list[0].hdl
            break;
          case 5:
            fatList[i].data = list[0].ldl
            break;
        }
      }
      that.setData({
        isData: true,
        createtime: list[0].createtime.substring(0,10),
        dataList: fatList,
      })
    }else{
      that.setData({
        isData: false,
        dataList: indexJson.fatList2,
        tipTxt: {
          tipTxt: '暂无测量数据',
          tipImg: '/resources/healthData/index/noData.png'
        }
      })
    }
  },

  //处理图表数据
  processingEchartData:function(list){
    if(list.length != 0){
      var that = this
      let cholesterolList = [] //总胆固醇
      let glycerolList = [] //甘油三酯
      let uricList = [] //尿酸
      let hdlList = [] //高密度
      let ldlList = [] //低密度
      let timeList = [] // 时间
      for(var i in list){
        timeList.push(list[i].date)
        cholesterolList.push(list[i].cholesterol)
        glycerolList.push(list[i].glycerol)
        uricList.push(list[i].uric)
        hdlList.push(list[i].hdl)
        ldlList.push(list[i].ldl)
      }
      that.setData({
        cholesterolList: cholesterolList,
        glycerolList: glycerolList,
        uricList: uricList,
        hdlList: hdlList,
        ldlList: ldlList,
        timeList: timeList,
        eName: '总胆固醇',
        ePadding: [0,0,0,48],
      })
      that.linechartsComponnet = that.selectComponent('#mychartLine');   
      LineChart = null
      that.getLineGraphData(that.data.cholesterolList,that.data.timeList);  //创建图表
    }
  },

  //处理数据
  processingData:function(list){
    // console.log(list)
    var that = this
    if(list.length != 0){
      for(var i in list){
        var date = list[i].createtime.substring(8,10)
        list[i].createtime = date + '日' 
      }
      that.setData({
        isData2: true,
        historyList: list,
      })
    }else{
      that.setData({
        isData2: false,
        tipTxt2: {
          tipTxt2: '暂无测量数据',
          tipImg2: '/resources/healthData/index/noDataSmall.png'
        }
      })
    }
  },

  //线图表
  getLineGraphData:function(data,time){
    if(data == null || time == null) return;
    var that = this
    if (!LineChart){
      that.init_LineEcharts(data,time); //初始化图表
    }else{
      that.setLineOption(data,time); //更新数据
    }
  },

  //初始化图表
  init_LineEcharts: function (data,time) {
    var that = this
    that.linechartsComponnet.init((canvas, width, height) => {
      // 初始化图表
      LineChart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      LineChart.showLoading({
        text : '正在努力的读取数据中...'
      });
      // Chart.setLineOption(this.getLineOption());
      that.setLineOption(data,time);
      // LineChart.dispatchAction({
      //   type: 'highlight',
      //   seriesIndex: 0,
      //   dataIndex: 0
      // });
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return LineChart;
    });
  },

  setLineOption: function (data,time) {
    LineChart.clear();  // 清除
    LineChart.setOption(this.getLineOption(data,time));  //获取新数据
  },

  //设置折线图表
  getLineOption: function (data,time) {
    var that = this
    // 指定图表的配置项和数据
    var option = {
      title : {
        text: '',
        subtext: ''
      },
      grid:{ 
        borderWidth:0,
        x:0,
        y:50,
        x2:0,
        y2:0,
        containLabel: true
      },
      xAxis: {
        type: 'category',
        show:true,
        boundaryGap:true,
        data : time,
        axisLine:{
          show:true,
          lineStyle:{
            color: 'white',
            width: 1,
          }
        },
        axisTick:{
          show:false
        },
        axisLabel:{
          show:true,
          color: 'white',
          interval: 0,
          formatter: '{value}',
          formatter:function(value){
            return util.setTime13(value) + '日'
          }
        },
      },
      yAxis: {
        type: 'value',
        name: that.data.eName,
        nameLocation: 'end',
        nameGap: 25,
        nameTextStyle:{
          color: '#76ebdc',
          padding: that.data.ePadding,
        },
        boundaryGap:false,
        show:true,
        scale: false,
        splitNumber:2,
        axisLine:{
          show: false,
        },
        axisTick: {
          show: false,
        },
        splitLine:{
          show:true,
          lineStyle:{
            color: 'rgba(255,255,255,0.3)',
          }
        },
        axisLabel:{
          show: true,
          inside: true,
          verticalAlign: 'bottom',
          margin: 0,
          color: '#76ebdc',
          formatter:function(value,index){
            return value
          }
        },
      },
      dataZoom:[
        {
          show: false,
          type:'slider',
          start: util.dataZoom(data),
          end: 100,
          left:'3%',
          right:'3%',
          maxValueSpan: 10,
        },
        {
          type: 'inside',
        },
      ],
      series : [{
        name:'',
        type:'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 12,
        itemStyle : {
          normal: {
            color: '#fff',
          }
        },
        emphasis:{
          label:{
            show: true,
            position: 'top',
            formatter:function(params){
              return params.data;
            }
          },
          itemStyle:{
            borderWidth: 12,
            borderType:'solid',
            borderColor: 'rgba(246,246,246,0.5)'
          }
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
                offset: 0, color: 'rgba(255,255,255,0)' // 0% 处的颜色
            }, {
                offset: 1, color: 'rgba(255,255,255,0.2)' // 100% 处的颜色
            }],
            globalCoord: false // 缺省为 false
          }
        },
        data:data
      }]
    };
    LineChart.hideLoading()
    return option;
  },

  //记录按钮
  recordBtn: function (e) {
    // console.log(e);
    var currentStatu = e.currentTarget.dataset.statu;
    this.anim(currentStatu);
  },

  //动画部分
  anim: function (currentStatu) {
    // 第1步：创建动画实例 
    var animation = wx.createAnimation({
      duration: 200,  //动画时长
      timingFunction: "linear", //线性
      delay: 0  //0则不延迟
    });
    
    // 第2步：这个动画实例赋给当前的动画实例
    this.animation = animation;
 
    // 第3步：执行第一组动画：Y轴偏移240px后(盒子高度是400px)，停
    animation.translateY(300).step();
 
    // 第4步：导出动画对象赋给数据对象储存
    this.setData({
      animationData: animation.export()
    })
    
    // 第5步：设置定时器到指定时候后，执行第二组动画
    setTimeout(function () {
      // 执行第二组动画：Y轴不偏移，停
      animation.translateY(0).step()
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象
      this.setData({
        animationData: animation
      })
      
      //完成
      if (currentStatu == "complete") {
        this.setData(
          {
            isHeight: false,
          }
        );
      }

      //取消
      else if (currentStatu == "cancel") {
        this.setData(
          {
            isHeight: false,
          }
        );
      }
    }.bind(this), 200)
  
    // 显示抽屉
    if (currentStatu == "open") {
      this.setData(
        {
          isHeight: true,
          title: '记录血脂',
          recordList: recordJson.bloodFat,
        }
      );
    }
  },

  //提交表单
  formSubmit:function(e){
    // console.log(e)
    var that = this
    let cholesterol = e.detail.value.cholesterol;//总胆固醇
    let glycerol = e.detail.value.glycerol;//甘油三酯
    let uric = e.detail.value.uric;//尿酸
    let hdl = e.detail.value.hdl;//HDL
    let ldl = e.detail.value.ldl;//LDL
    if (cholesterol == "" || glycerol == "" || uric == "" || hdl == "" || ldl == ""){
      util.showModal('提示','请输入完整信息')
      return
    }
    if(cholesterol.length > 0)
    {
      let type= 'number'
      let validation = util.validation(cholesterol,type)
      if(!validation){
        util.showModal('提示','总胆固醇输入不正确')
        return
      }
    }
    if(glycerol.length > 0)
    {
      let type= 'number'
      let validation = util.validation(glycerol,type)
      if(!validation){
        util.showModal('提示','甘油三酯输入不正确')
        return
      }
    }
    if(uric.length > 0)
    {
      let type= 'number'
      let validation = util.validation(uric,type)
      if(!validation){
        util.showModal('提示','尿酸输入不正确')
        return
      }
    }
    if(hdl.length > 0)
    {
      let type= 'number'
      let validation = util.validation(hdl,type)
      if(!validation){
        util.showModal('提示','HDL输入不正确')
        return
      }
    }
    if(ldl.length > 0)
    {
      let type= 'number'
      let validation = util.validation(ldl,type)
      if(!validation){
        util.showModal('提示','LDL输入不正确')
        return
      }
    }
    that.save(cholesterol,glycerol,uric,hdl,ldl);
  },

  //保存信息
  save:function(cholesterol,glycerol,uric,hdl,ldl){
    var that = this
    wx.request({
      url: app.globalData.apiUrl +'/add_user_xuezhi', //接口地址
      data: {
        userid: app.globalData.userId,
        cholesterol: cholesterol,
        glycerol: glycerol,
        uric: uric,
        hdl: hdl,
        ldl: ldl,
      },
      method: 'post',
      header: {
          'content-type': 'application/x-www-form-urlencoded' //默认值
      },
      success: function (res) {
        // console.log(res)
        if(res.data.code == '200'){
          util.showToast('保存成功','success')         
          that.getData(that.data.date);
        }else{
          util.showModal('提示','记录失败')
          return;
        }
      }
    })
  },

  //选择导航栏
  switchNav(event){
    var that = this
    var cur = event.currentTarget.dataset.current;
    if (that.data.currentTab == cur) {
      return false;
    } else {
      that.setData({
          currentTab: cur
      })
      if(that.data.eName){
        that.setEchartsData(cur)        
      }
    }
  },

  //给图表赋值
  setEchartsData:function(cur){
    var that = this
    switch (cur) {
      case 0:
        //总胆固醇
        that.setData({
          eName: '总胆固醇',
          ePadding: [0,0,0,48],
        })
        that.getLineGraphData(that.data.cholesterolList,that.data.timeList);
        break;
      case 1:
        //总胆固醇
        that.setData({
          eName: '甘油三酯',
          ePadding: [0,0,0,48],
        })
        that.getLineGraphData(that.data.glycerolList,that.data.timeList);
        break;
      case 2:
        //甘油三酯
        that.setData({
          eName: '尿酸',
          ePadding: [0,0,0,24],
        })
        that.getLineGraphData(that.data.uricList,that.data.timeList);
        break;
      case 3:
        //HDL
        that.setData({
          eName: 'HDL',
          ePadding: [0,0,0,26],
        })
        that.getLineGraphData(that.data.hdlList,that.data.timeList);
        break;
      case 4:
        //LDL
        that.setData({
          eName: 'LDL',
          ePadding: [0,0,0,26],
        })
        that.getLineGraphData(that.data.ldlList,that.data.timeList);
        break;
    }
  },

  //阻止穿透
  preventTouchMove: function () {
    // console.log('stop user scroll it!');
    return;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    LineChart = null
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    LineChart = null
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    // return {
    //   title: 'PAPN体重管理',
    //   path: 'pages/index/index',
    //   success: function(res) {
    //     // res.shareTickets 
    //   },
    //   fail: function(res) {
    //       console.log(res)
    //   }
    // }
  }
})